package com.douyu.bolt;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;

/**
 * @Auther: xiaoyuan
 * @Date: 2019/6/19
 * @Description:
 */
public class ReportBolt extends BaseRichBolt {

    private HashMap<String,Long> counts = null;
    private OutputCollector collector;

    public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
        this.counts = new HashMap<String, Long>();
        this.collector = outputCollector;
    }

    public void execute(Tuple tuple) {
        String word = tuple.getStringByField("word");
        Long count = tuple.getLongByField("count");
        this.counts.put(word,count);
        if(word.equals("i")){
            System.out.println("report fail:"+word);
            this.collector.fail(tuple);
        }else{
            System.out.println("report ack:"+word);
            //this.collector.ack(tuple);
        }

//        System.out.println("report ack:"+word);
//        this.collector.ack(tuple);

    }

    public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {

    }

    public void cleanup(){
        System.out.println("---最后结果---");
        List<String> keys = new ArrayList<String>();
        keys.addAll(this.counts.keySet());
        Collections.sort(keys);
        for(String key:keys){
            System.out.println(key+":"+this.counts.get(key));
        }
        System.out.println("-------------");
    }
}
